<?php
/**
 * @author li ming
 * @date 2021-10-12
 */
namespace Modules\User\Services\Api;

use App\Models\Area;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\User\Entities\Favorite;
use Modules\User\Entities\UserAddress;
use Modules\User\Validate\Api\AddressValidate;
use Illuminate\Support\Facades\Cache;
use function Sodium\compare;

class UserAddressServices extends BaseService
{

    /**
     * @var Request
     */
    private $request;


    /**
     * @var AddressValidate
     */
    private $validate;
    
    /**
     * UserServices constructor.
     *
     * @param Request $request
     * @author tan bing
     * @date 2021-08-11 12:36
     */
    public function __construct(Request $request, AddressValidate $validates)
    {
        $this->request = $request;
        $this->validate = $validates;// 验证联系电话
    }


    /**
     * 获取地址信息
     * @return array
     */
    public function getArea()
    {
        $seconds = 60*60*24*120;
        return Cache::remember('api-area', $seconds, function () {
            $list = Area::where([
                ["level", "=", "province"],
            ])->select("id", "name")->get()->toArray();
            foreach ($list as &$item){
                $item["list"] = Area::where([
                    ["level", "=", "city"],
                    ["parent_id", "=", $item["id"]],
                ])->select("id", "name")->get()->toArray();
                foreach ($item["list"] as &$child){
                    $child["list"] = Area::where([
                        ["level", "=", "district"],
                        ["parent_id", "=", $child["id"]],
                    ])->select("id", "name")->get()->toArray();
                }
            }
            return $list;
        });
    }

    /**
     * 新增地址
     * @return bool
     * @throws \Exception
     */
    public function add()
    {
        $param = $this->request->input();
        if(!$this->validate->scene("add")->check($param)) throw new \Exception($this->validate->getError());
        
        // 验证联系电话
        $isMob = "/^1[34578]{1}\d{9}$/";
        $isTel ="/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        
        if(!preg_match($isMob,$param['phone']) && !preg_match($isTel,$param['phone'])){
            throw new \Exception("电话格式错误");
        }
        $province = Area::where([
            ["id", "=", $param["province_id"]],
            ["level", "=", "province"],
        ])->first();
        if(!$province) throw new \Exception("省份不存在");

        $city = Area::where([
            ["id", "=", $param["city_id"]],
            ["parent_id", "=", $param["province_id"]],
            ["level", "=", "city"],
        ])->first();
        if(!$city) throw new \Exception("城市不存在");

        $district = Area::where([
            ["id", "=", $param["region_id"]],
            ["parent_id", "=", $param["city_id"]],
            ["level", "=", "district"],
        ])->first();
        if(!$district) throw new \Exception("区/县不存在");

        $user_id = $this->request->attributes->get('userId');
        if($user_id <= 0) throw new \Exception("用户不存在");

        $model = new UserAddress();
        $model->name = $param["name"];
        $model->phone = $param["phone"];
        $model->user_id = $user_id;
        $model->province_id = $province->id;
        $model->province = $province->name;
        $model->city_id = $city->id;
        $model->city = $city->name;
        $model->region_id = $district->id;
        $model->region = $district->name;
        $model->detail = $param["detail"];
        $model->is_default = 1;
        if(UserAddress::where("user_id", $user_id)->where("is_delete", 2)->first()) $model->is_default = 2;
        if(!$model->save()) throw new \Exception("新增地址失败");
        return true;
    }

    /**
     * 新增授权的地址
     * @return bool
     * @throws \Exception
     */
    public function empowerAdd()
    {
        $param = $this->request->input();
        if(!$this->validate->scene("empower_add")->check($param)) throw new \Exception($this->validate->getError());
        // 验证联系电话
        $isMob = "/^1[34578]{1}\d{9}$/";
        $isTel ="/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        if(!preg_match($isMob,$param['phone']) && !preg_match($isTel,$param['phone'])){
            throw new \Exception("电话格式错误");
        }
        $province = Area::where([
            ["name", "=", $param["province"]],
            ["level", "=", "province"],
        ])->first();

        $city = Area::where([
            ["name", "=", $param["city"]],
            ["level", "=", "city"],
        ])->first();

        $district = Area::where([
            ["name", "=", $param["region"]],
            ["level", "=", "district"],
        ])->first();

        $user_id = $this->request->attributes->get('userId');
        if($user_id <= 0) throw new \Exception("用户不存在");

        $model = new UserAddress();
        $model->name = $param["name"];
        $model->phone = $param["phone"];
        $model->user_id = $user_id;
        $model->province_id = $province->id ?? 0;
        $model->province = $param["province"];
        $model->city_id = $city->id ?? 0;
        $model->city = $param["city"];
        $model->region_id = $district->id ?? 0;
        $model->region = $param["region"];
        $model->detail = $param["detail"];
        $model->is_default = 1;
        if(UserAddress::where("user_id", $user_id)->where("is_delete", 2)->first()) $model->is_default = 2;
        if(!$model->save()) throw new \Exception("新增地址失败");
        return true;
    }

    /**
     * 编辑地址
     * @return bool
     * @throws \Exception
     */
    public function edit()
    {
        $param = $this->request->input();
        
        // 验证联系电话
        $isMob = "/^1[34578]{1}\d{9}$/";
        $isTel ="/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        
        if(!preg_match($isMob,$param['phone']) && !preg_match($isTel,$param['phone'])){
            throw new \Exception("电话格式错误");
        }
        if(!$this->validate->scene("edit")->check($param)) throw new \Exception($this->validate->getError());
        
        $province = Area::where([
            ["id", "=", $param["province_id"]],
            ["level", "=", "province"],
        ])->first();
        if(!$province) throw new \Exception("省份不存在");

        $city = Area::where([
            ["id", "=", $param["city_id"]],
            ["parent_id", "=", $param["province_id"]],
            ["level", "=", "city"],
        ])->first();
        if(!$city) throw new \Exception("城市不存在");

        $district = Area::where([
            ["id", "=", $param["region_id"]],
            ["parent_id", "=", $param["city_id"]],
            ["level", "=", "district"],
        ])->first();
        if(!$district) throw new \Exception("区/县不存在");

        $user_id = $this->request->attributes->get('userId');
        if($user_id <= 0) throw new \Exception("用户不存在");

        $model = UserAddress::where([
            ["address_id", "=", $param["address_id"]],
            ["is_delete", "=", 2],
            ["user_id", "=", $user_id],
        ])->first();
        if(!$model) throw new \Exception("地址信息不存在");

        $model->name = $param["name"];
        $model->phone = $param["phone"];
        $model->province_id = $province->id;
        $model->province = $province->name;
        $model->city_id = $city->id;
        $model->city = $city->name;
        $model->region_id = $district->id;
        $model->region = $district->name;
        $model->detail = $param["detail"];
        if(!$model->save()) throw new \Exception("更新地址失败");
        return $model;
    }

    /**
     * @param string $type save_default = 设置默认地址  || del = 删除地址
     */
    public function saveStatus(string $type)
    {
        $param = $this->request->input();
        if(!$this->validate->scene($type)->check($param)) throw new \Exception($this->validate->getError());

        $user_id = $this->request->attributes->get('userId');
        if($user_id <= 0) throw new \Exception("用户不存在");

        $model = UserAddress::where([
            ["address_id", "=", $param["address_id"]],
            ["is_delete", "=", 2],
            ["user_id", "=", $user_id],
        ])->first();
        if(!$model) throw new \Exception("地址信息不存在");

        switch ($type){
            case "save_default":
                DB::beginTransaction();
                try {
                    UserAddress::where([
                        ["user_id", "=", $user_id],
                        ["is_default", "=", 1],
                    ])->update(["is_default" => 2]);

                    $model->is_default = 1;
                    if(!$model->save()) throw new \Exception("设置默认地址失败");
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    throw new \Exception($e->getMessage());
                }
                break;
            case "del":
                $model->is_delete = 1;
                if(!$model->save()) throw new \Exception("删除地址失败");
                break;
            default:
                throw new \Exception("修改类型值不存在");
        }
        return true;
    }

    /**
     * 用户地址列表
     */
    public function getPageList()
    {
        $user_id = $this->request->attributes->get('userId');
        if($user_id <= 0) throw new \Exception("用户不存在");

        $page = intval($this->request->input('page',1));
        $limit = intval($this->request->input('limit',10));
        //求偏移量
        $offset = ($page-1)*$limit;

        $where = [
            ["user_id", "=", $user_id],
            ["is_delete", "=", 2],
        ];

        $total = UserAddress::where($where)->count();
        $list = UserAddress::where($where)->offset($offset)->limit($limit)->orderBy("address_id","desc")->get();
        return compact("total", "list");
    }

}